<template>
	<view class="home">
		<!-- <button @click="getDevices">获取设备路径列表</button> -->

		<button @click="open">打开串口</button>
		<button @click="off">关闭串口</button>
		<button @click="state">串口状态</button>
		<button @click="send">发送消息</button>
		<!-- <web-view  src="www.baidu.com"></web-view> -->

		<button>底部</button>
		<view class="">
			传值：{{dataType}}
		</view>
	</view>
</template>

<script>
	const serialPort = uni.requireNativePlugin('Fvv-UniSerialPort')
	export default {
		name: "serialPort",
		props: ['dataType'],
		data() {
			return {
				devicePath: '',
				recType: "ASCII",
				sendType: "Hex",
				isOpen: false,
				recText: "",
				
				relevant: '', //子传父
			}
		},
		methods: {
			// 字传父
			relevantFn(data) {
				this.$emit("clickPort", data)
			},
			//获取所有设备路径
			getDevices() {
				serialPort.getAllDevicePath(res => {
					this.devicePath = res[1]
					console.log('路径', res) //路径列表
				})
			},
			off() {
				serialPort.close()
			},
			state() {
				let isOpen = serialPort.isOpen()
				console.log('isOpen', isOpen);
			},
			//打开串口
			open() {
				console.log('this.dataType', this.dataType);
				serialPort.setPath('/dev/ttyUSB0')
				serialPort.setBaudRate(9600)
				serialPort.setStopBits(1)
				serialPort.setDataBits(8)
				serialPort.open(res => {
					console.log('res', res);
					if (!res.status) {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: "none"
						});
						return
					}
					uni.showToast({
						title: "已打开",
						duration: 2000,
					});
					this.onMessage()

				})
			},
			addMessage(type, msg) {
				this.recText += (type === 'rec' ? "→" : "←") + msg + "\r\n";
			},
			//监听数据 
			onMessage() {
				serialPort.onMessageHex(rec => {
					console.log("16进制",rec)
					this.relevantFn(rec)
				}, send => {
					console.log('send', send)
				})
			},
			//发送消息
			send() {
				if (this.sendType === 'ASCII') {
					serialPort.sendASCII('dfgdhfghf')
				}
				if (this.sendType === 'Hex') {
					serialPort.sendHex('fghfg456746')
				}
			},
		},
		mounted() {
			this.open()
		}
	}
</script>

<style>
	.content {
		flex: 1;
	}

	.uni-list-cell {
		flex-direction: row;
	}

	.uni-list-cell-picker {
		flex-direction: row;
		justify-content: space-between;
		flex: 1;
		padding: 20rpx;
	}

	.device-msg-container {
		flex: 1;
	}

	.device-msg {
		flex: 1;
	}

	.device-msg-head {
		background-color: #efefef;
		flex-direction: row;
		justify-content: space-between;
		padding: 10rpx;
	}

	.device-msg-radio {
		flex-direction: row;
	}

	.device-msg-content {
		flex: 1;
		padding: 10rpx;
	}
</style>